<template>
	<el-drawer
		v-model="drawerVisible"
		@closed="resetForm(ruleFormRef)"
		:destroy-on-close="true"
		:close-on-click-modal="false"
		size="50%"
		:title="`${drawerProps.title}文章`"
	>
		<el-form ref="ruleFormRef" :rules="rules" :model="addOrUpdateForm" status-icon label-width="80" label-position="right">
			<el-form-item label="文章标题" prop="articleTitle">
				<el-input placeholder="请输入" v-model="addOrUpdateForm.articleTitle"></el-input>
			</el-form-item>
			<el-form-item label="文章分类" prop="categoryIds">
				<div style="display: flex; width: 100%">
					<el-select
						v-model="addOrUpdateForm.categoryIds"
						style="width: auto"
						placeholder="请选择"
						multiple
						@change="handleSelectChange"
					>
						<el-option
							v-for="(item, index) in categoryData"
							:key="index"
							:label="item.name"
							:value="item.id"
							:disabled="handleOptionChange(item)"
						></el-option>
					</el-select>
					<el-link @click="() => router.push('/information/informationType')" style="margin-left: 10px" type="primary"
						>类型管理</el-link
					>
				</div>
			</el-form-item>
			<el-form-item prop="cover" label="封面图">
				<uploadImg v-model:image-url="addOrUpdateForm.cover">
					<template #tip>
						<p>支持格式：jpg、png ，单个文件不能超过20MB，建议尺寸100*100</p>
					</template>
				</uploadImg>
			</el-form-item>

			<el-form-item label="分享摘要" prop="shareSummary">
				<el-input placeholder="请输入" v-model="addOrUpdateForm.shareSummary"></el-input>
			</el-form-item>

			<el-form-item label="文章内容" prop="articleContent">
				<WangEditor v-model:value="addOrUpdateForm.articleContent"></WangEditor>
			</el-form-item>

			<el-form-item label="排序" prop="sort">
				<el-input placeholder="请输入" v-model.number="addOrUpdateForm.sort"></el-input>
			</el-form-item>
			<el-form-item label="状态">
				<el-radio-group v-model="addOrUpdateForm.isEnable">
					<el-radio :label="true">启用</el-radio>
					<el-radio :label="false">禁用</el-radio>
				</el-radio-group>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="resetForm(ruleFormRef)">取消</el-button>
			<el-button type="primary" @click="handleSubmit">保存</el-button>
		</template>
	</el-drawer>
</template>

<script setup lang="ts" name="basetable">
import { ref, reactive, watch, nextTick } from "vue";
import WangEditor from "@/components/MyWangEditor/index.vue";
import { ElMessage } from "element-plus";
import uploadImg from "@/components/Upload/Img.vue";
import api from "@/api/modules/news";
import category from "@/api/modules/category";
import type { FormInstance, FormRules } from "element-plus";
import { useRouter } from "vue-router";
const router = useRouter();
const ruleFormRef = ref<FormInstance>();
interface selectItem {
	name: string;
	id: string;
}
interface DrawerProps {
	title: string;
	isView: boolean;
	id: string | null;
	api?: any;
	getTableList?: () => void;
}
const categoryData = ref<selectItem[]>([]);
const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
	isView: false,
	title: "",
	id: ""
});
// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
	drawerProps.value = params;
	drawerVisible.value = true;
};
/**添加或更新常量 */
const addOrUpdateForm = ref({
	articleTitle: "",
	categoryIds: [],
	shareSummary: "",
	articleContent: "",
	sort: "" as string | number,
	isEnable: true,
	cover: "",
	id: ""
});

const rules = reactive<FormRules>({
	articleTitle: [
		{ required: true, message: "文章标题不能为空", trigger: "blur" },
		{ max: 50, message: "文章标题最大长度不能超过50", trigger: "blur" }
	],
	categoryIds: [
		{
			required: true,
			message: "请选择文章分类",
			trigger: "change"
		}
	],
	cover: [
		{
			required: true,
			message: "没有选中封面图",
			trigger: "blur"
		}
	],
	shareSummary: [
		{
			required: true,
			message: "摘要不能为空",
			trigger: "blur"
		},
		{ max: 50, message: "摘要最大长度不能超过50", trigger: "blur" }
	],
	articleContent: [
		{
			required: true,
			message: "文章内容不能为空",
			trigger: "blur"
		}
	]
});
/**获取资讯分类列表 */
const getCategorys = (companyId: string) => {
	categoryData.value = [];
	category.GetAllCategorysApi("", companyId).then(res => {
		let { data } = res.result as any;
		data.unshift({ name: "全部", id: "-1" });
		categoryData.value = data;
	});
};
getCategorys("");
// 编辑资讯回显。
const getNewsById = async () => {
	nextTick(async () => {
		if (!drawerProps.value.id) return;
		let { result } = await api.GetByIdUpdateNewsApi(drawerProps.value.id);
		let { data, code } = result as any;
		if (code != 200) return;
		addOrUpdateForm.value = data;
	});
};
// 关闭抽屉刷新数据
const resetForm = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	drawerVisible.value = false;
};
// 选择资讯分类
const handleSelectChange = (arr: any) => {
	if (arr.includes("-1" as never)) {
		addOrUpdateForm.value.categoryIds = ["-1" as never];
	}
};
const handleOptionChange = (item: any) => {
	addOrUpdateForm.value.categoryIds?.includes("-1" as never) && item.id !== "-1";
};
watch(
	() => drawerVisible.value,
	val => {
		if (!val) return;
		getNewsById();
	}
);
const handleSubmit = () => {
	ruleFormRef.value!.validate(async valid => {
		if (!valid) return;
		try {
			// 如果用户点击的是全部，将全部分类加入分类id列表中
			if (addOrUpdateForm.value.categoryIds.includes("-1" as never)) {
				addOrUpdateForm.value.categoryIds = categoryData.value.map((item: any, index: number) => {
					if (index == 0) return;
					return (item = item.id);
				}) as never;
			}
			addOrUpdateForm.value.sort = addOrUpdateForm.value.sort == "" ? 0 : addOrUpdateForm.value.sort;
			await drawerProps.value.api!(addOrUpdateForm.value);
			ElMessage.success({ message: `${drawerProps.value.title}资讯成功！` });
			drawerProps.value.getTableList!();
			drawerVisible.value = false;
		} catch (error) {
			console.log(error);
		}
	});
};
defineExpose({
	acceptParams
});
</script>
